package com.essence.grabiec104.grab.router;

import cn.hutool.json.JSONUtil;
import com.essence.common.model.EnumTypeAdapter;
import com.essence.grabiec104.grab.executor.SaveExecutor;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.zeromq.SocketType;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;
import org.zeromq.ZMQException;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;

@Component("Publisher")
public class Publisher {
    private static final Logger LOG = LoggerFactory.getLogger(Publisher.class);
    public enum ZCtxParam {
        INSTANCE;

        private final ZContext publishCtx;
        private final String inprocName;

        ZCtxParam() {
            this.publishCtx = new ZContext(1);
            this.inprocName = "inproc://publish_worker";
        }

        public ZContext getPublishCtx() {
            return publishCtx;
        }

        public String getInprocName() {
            return inprocName;
        }
    }
    private ZMQ.Socket router;
    private ZMQ.Socket pullSocket;
    private volatile boolean running = true;
    @Value("${grabber.port}")
    private int port;
    @Autowired
    private RouterService routerService;


    private final List<String> clientIds = new CopyOnWriteArrayList<>();

    private final Gson gson = new GsonBuilder()
            .registerTypeAdapterFactory(new TypeAdapterFactory() {
                @Override
                public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
                    Class<? super T> rawType = type.getRawType();
                    if (!Enum.class.isAssignableFrom(rawType)) {
                        return null;
                    }
                    return (TypeAdapter<T>) new EnumTypeAdapter();
                }
            })
            .create();

    @PostConstruct
    public void init() {
        router = ZCtxParam.INSTANCE.getPublishCtx().createSocket(SocketType.ROUTER);
        router.bind("tcp://*:" + port);
        pullSocket = ZCtxParam.INSTANCE.getPublishCtx().createSocket(SocketType.PULL);
        pullSocket.bind(ZCtxParam.INSTANCE.getInprocName());

        // 创建Poller并注册两个套接字
        ZMQ.Poller poller = ZCtxParam.INSTANCE.getPublishCtx().createPoller(2);
        poller.register(router, ZMQ.Poller.POLLIN);
        poller.register(pullSocket, ZMQ.Poller.POLLIN);
        ExecutorService executor = SaveExecutor.addPool("grabber_publisher", 1);
        executor.execute(() -> {
            while (running) {
                poller.poll();
                if (poller.pollin(0)) {
                    handlerRequest();
                }
                if (poller.pollin(1)) {
                    handlerPublish();
                }
            }
        });
    }

    /**
     * @brief 处理请求-应答
     * @details router socket接收到请求后, 会调用此方法进行处理, 如果clientId不在clientIds中, 则将其加入。如果是ping-pong消息, 则直接返回。
     * 其它消息, 才会调用routerService.invokeRouter方法进行处理。
     */
    private void handlerRequest() {
        String clientId = router.recvStr();
        if (!clientIds.contains(clientId)) {
            clientIds.add(clientId);
        }
        String method = router.recvStr();
        LOG.info("handlerRequest: {}", method);
        byte[] body = router.recv();
        // 如果是ping-pong消息, 则直接返回
        if (method.equals("ping")) {
            LOG.info("{} ping", clientId);
            router.sendMore(clientId);
            router.sendMore("pong");
            router.send(body, ZMQ.DONTWAIT);
            return;
        }

        try {
            Object result = routerService.invokeRouter(method, body);
            router.sendMore(clientId);
            router.sendMore(method);
            if(result instanceof String) {
                router.send((String)result);
            }
            else if(result instanceof Integer) {
                router.send(String.valueOf(result));
            }
            else if(result instanceof Boolean) {
                router.send(String.valueOf(result));
            }
            else if(result instanceof Long) {
                router.send(String.valueOf(result));
            }
            else if(result instanceof Double) {
                router.send(String.valueOf(result));
            }
            else {
                String response = gson.toJson(result);
                router.send(response.getBytes(StandardCharsets.UTF_8));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @brief 处理发布（广播消息）
     * @details mainPair socket接收到消息后, 会调用此方法进行处理, 将消息广播给所有客户端, 如果客户端连接异常, 则将其从clientIds中移除
     */
    private void handlerPublish() {
        String topic = pullSocket.recvStr();
        LOG.info("handlerPublish: {}", topic);
        byte[] body = pullSocket.recv();
        List<String> invalidClients = new ArrayList<>();
        for (String clientId : clientIds) {
            try {
                router.sendMore(clientId);
                router.sendMore(topic);
                boolean isSent = router.send(body, ZMQ.DONTWAIT);
                if (!isSent) {
                    LOG.warn("客户端 {} 发送失败（EAGAIN），将移除", clientId);
                    invalidClients.add(clientId);
                }
            } catch (ZMQException e) {
                if (e.getErrorCode() == ZMQ.Error.EHOSTUNREACH.getCode()) {
                    LOG.warn("客户端 {} 连接异常（EHOSTUNREACH），将移除", clientId);
                    invalidClients.add(clientId);
                }
            }
        }

        // 清理失效客户端
        if (!invalidClients.isEmpty()) {
            clientIds.removeAll(invalidClients);
        }
    }


    @PreDestroy
    public void destroy() {
        running = false; // 停止事件循环
        ZCtxParam.INSTANCE.getPublishCtx().close();
    }
}
